#!/bin/bash
################################################################################
# Store this file as .git/hooks/commit-msg in your repository in order to
# enforce checking for proper commit message format before actual commits. You
# may need to make the script executable by 'chmod +x .git/hooks/commit-msg'.
################################################################################
filename="$1"
lineno=0

error() {
    echo "请检查您所提交的消息日志的格式!"
    echo "$1"
    echo "$2"
    echo "$3"
    echo ""
    exit 1
}

while read -r line
do
    # Ignore comment lines (don't count line number either)
    [[ "$line" =~ ^#.* ]] && continue

    let lineno+=1
    length=${#line}

    # Subject line tests
    if [[ $lineno -eq 1 ]]
    then
        # Compatible with "Merge*************"
        [[ "$line" =~ ^Merge.* ]] && continue

        # Compatible with "Revert *************"
        [[ "$line" =~ ^Revert.* ]] && continue

        [[ $length -gt 60 ]] && error "Limit the subject line to 60 characters"

        type=$(echo $line | awk 'BEGIN{FS=":"} {print $1}')
        
        [[ ${#type} -eq 0 ]] && error "提交错误：Type参数不能为空" "请参考规则:git commit -m <type>[optional scope]: <description>" "参考文章：https://www.cnblogs.com/qiqi715/p/12737297.html"

        if [[ ! "$type" =~ ^(feat|fix|docs|style|refactor|perf|test|chore|revert|ci|build)$ && ! "$type" =~ ^(feat|fix|docs|style|refactor|perf|test|chore|revert|ci|build)\(.*\)$ ]]
        then
            error "Type参数必须符合以下类型：[feat,fix,docs,style,refactor,perf,test,chore,revert,ci,build]" "例子：git commit -m 'feat: 增加 xxx 功能'" "参考文章：https://www.cnblogs.com/qiqi715/p/12737297.html"
        fi
    fi

    # Rules related to the commit message body
    [[ $lineno -eq 2 ]] && [[ -n $line ]] && error "Separate subject from body with a blank line"
    [[ ! $lineno -gt 1 ]] && [[ $length -gt 72 ]] && error "Wrap the body at 72 characters"
done < "$filename"


exit 0

